<?php
require 'functions.php';

$session = new \Models\MySession();

if($_SESSION['isLogged'] != 2) {
    header('Location: index.php');
    exit;
}

// ******** List of authors START ***************
$authors = new Models\Authors;
$authors->setAllFromOneTable('authors', 'author_name', 'asc');
$queryResult = $authors->getAllFromOneTable();
foreach ($queryResult as $value) {
   $data['authors'][$value['author_id']] = $value['author_name'];   
}
// ******** List of authors END *****************


if($_POST){
    if(!$_POST['book_name']) {
       echo 'Fill Book title <br>'; 
    }   
    if(!isset($_POST['authors'])) {
        echo 'Select author';
  
    } else {
        $books = new Models\Books();
        try {
            $books->saveBook($_SESSION['isLogged'], $_POST['book_name'], 
                    $_POST['authors']); 
        } catch (\Exception $exc) {
            echo  $exc->getMessage();
        } 
    }   
} 

$data['userGreeting'] = '';
if($_SESSION and !empty($_SESSION['userId'] )){
    try {
        $userName = Models\User::getUserName($_SESSION['userId']); 
        $data['userGreeting'] = 'Hi <b>'.$userName.'</b>';   
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
}

@$data['isLogged'] = $_SESSION['isLogged'];
$data['title'] = 'Add new book';
$data['content'] = './public_html/add_book_public.php';
$data['header'] = './inc/header.php';
render($data, $layout);
